package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.POIUtils;
import com.itheima.pojo.OrderSetting;
import com.itheima.sercice.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@RestController
@RequestMapping("ordersetting")
public class OrderSettingController {


    @Autowired
    private OrderSettingService orderSettingService;

    /**
     * 文件上传
     *
     * @param excelFile
     * @return
     */
    @PostMapping("upload")
    public Result upload(MultipartFile excelFile) {
        try {
            //使用POI解析Excel表格
            List<String[]> excel = POIUtils.readExcel(excelFile);
            //转换数据类型
            List<OrderSetting> list = new ArrayList<>();
            for (String[] strings : excel) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                Date orderDate = sdf.parse(strings[0]);
                String number = strings[1];
                OrderSetting orderSetting = new OrderSetting(orderDate, Integer.parseInt(number));
                list.add(orderSetting);
            }
            orderSettingService.add(list);
        } catch (Exception e) {
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
        return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }


    /**
     * 根据日期修改可预约人数
     * @param orderSetting
     * @return
     */
    @PostMapping("editNumberByOrderDate")
    public Result editNumberByOrderDate(@RequestBody OrderSetting orderSetting) {
        orderSettingService.editNumberByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
    }



    /**
     * 根据年月查询对应的预约设置信息
     * @param month
     * @return
     */
    @RequestMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String month) {//参数格式为：2019-03

        try {
            List<OrderSetting> list = orderSettingService.getOrderSettingByMonth(month);
            //获取预约设置数据成功
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,MessageConstant.GET_ORDERSETTING_FAIL);
    }

    /**
     * 模板下载
     * @param response
     * @return
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response,String filename){
        orderSettingService.download(response,filename);

    }

}
